const config = {
	// 请求拦截器
	beforeRequest(options = {}) {
		return new Promise((resolve, reject) => {
			options.url = options.url
			options.method = options.method || 'GET';
			options.data = options.data;
			options.header = options.header
			resolve(options)
		})
	},
	// 响应拦截器
	handleResponse(result) {
		return new Promise((resolve, reject) => {
			const {
				data
			} = result;
			const dataHandler = data;
			resolve(dataHandler)
		})
	}
}


const otherRequest = (method, url, data, header = {}) => {

	let options = {
		method: method,
		url: url,
		data: data,
		dataType: 'json',
		header: header
	}

	return config.beforeRequest(options).then(opt => {
		return new Promise((resolve, reject) => {
			uni.request(Object.assign(opt, {
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					reject(err)
				}
			}))
		})
	}).then(res => {
		return config.handleResponse(res)
	})
}

export default function(method = 'get', url = '', data = {}, header = {}) {
	method = method.toLowerCase();
	if (method == 'post') {
		return otherRequest('post', url, data, header)
	} else if (method == 'get') {
		return request('get', url, data, header)
	} else if (method == 'delete') {
		return otherRequest('delete', url, {
			params: data
		})
	} else if (method == 'put') {
		return otherRequest('put', url, data, header)
	} else {
		console.error('未知的method' + method)
		return false
	}
}